package java6699.lesson14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @program: java_zzx
 * @description:
 * @author: zzx
 * @create: 2022-12-07 19:10
 **/
public class OneServer6699 {
    private int port;

    public OneServer6699() {
        port = 8086;
    }

    public void start() {
        System.out.println(port+"服务已启动");
        try (ServerSocket ss = new ServerSocket(port);
             Socket socket = ss.accept()) {

            session(socket);//开始与客户端通话
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void session(Socket socket) throws IOException {
        //连接成功，在控制台上显示客户端的信息
        String client = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
        System.out.println(client + "，已接入");

        // 包装Socket中的IO字节流
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintStream printer = new PrintStream(socket.getOutputStream());

        // 连接成功，先向客户端发送欢迎用语。
        printer.println("欢迎致电"+port+"服务平台，很高兴为您服务……");

        Scanner input = new Scanner(System.in);// 用Scanner实现键盘输入
        int count = 1;
        String problem = null;
        while ((problem = reader.readLine()) != null) {// 接收客户端的信息
            if ("谢谢".equals(problem.trim())) {
                printer.println("再见");
                System.out.print("结束：" + client);
                break;
            }
            System.out.println("问" + count++ + "：" + problem);
            System.out.print("请输入答案：");
            // 向客户端发送信息
            printer.println(input.nextLine());
        }
    }

    public static void main(String[] args) throws Exception {
        new OneServer6699().start();
    }
}
